﻿/*
 * @(#)ReadFeed	gadget 24/01/07
 * Copyright 2007  Hemakumar M. All rights reserved.
 */

plugin.onShowOptionsDlg = ShowOptionsDlg;

var httpReq = null;
var doc = null; //Xml Document

plugin.SetFlags(gddPluginFlagNone, gddContentFlagHaveDetails);

var interval = 600; //10 mins

var urlsDefault = new Array();
urlsDefault =["http://z.about.com/6/nl/rss/todaysl.xml",
"http://www.101cookbooks.com/index.rdf",
"http://ask.yahoo.com/ask/index.xml",
"http://rss.cnn.com/rss/cnn_latest.rss",
"http://www.cricinfo.com/rss/index.rdf",
"http://www.ciol.com/RSS/CIOL-ITNews.xml",
"http://dictionary.reference.com/wordoftheday/wotd.rss",
"http://sports.espn.go.com/espn/rss/news",
"http://www.expressindia.com/syndications/ei.xml",
"http://www.fodors.com/blog/index.rdf",
"http://www.forbes.com/feeds/popstories.xml",
"http://www.brainyquote.com/link/quotefu.rss",
"http://www.glamsham.com/rss/glamRss.xml",
"http://www.iht.com/rss/frontpage.xml",
"http://www.funtoosh.com/rss/latest_jokes.php",
"http://www.medindia.net/rss2.0/rss.xml",
"http://cricket.indiatimes.com/rssfeeds/864838.cms",
"http://www.nytimes.com/services/xml/rss/nyt/Travel.xml",
"http://googleblog.blogspot.com/atom.xml",
"http://www.brainyquote.com/link/quotebr.rss",
"http://www.microsite.reuters.com/rss/oddlyEnoughNews",
"http://rss.techtree.com/cgi-bin/itn/rss/index.cgi?ws=tt&feed=recentstuff",
"http://economictimes.indiatimes.com/rssfeeds/1286551815.cms",
"http://www.expressindia.com/syndications/fe.xml",
"http://www.fool.com/About/headlines/rss_headlines.asp",
"http://www.wired.com/news/feeds/rss2/0,2610,,00.xml",
"http://rss.news.yahoo.com/rss/entertainment",
"http://news.zdnet.com/2509-1_22-0-5.xml"];

function getSelectedUrl() {
 var selectedurl = 0;
 if( !options.exists("selectedurl"))
    options("selectedurl")= selectedurl;
  else
    selectedurl = options("selectedurl");

  var ind = parseInt(selectedurl);

  if(ind>=urlsDefault.length){
    ind = 0;
    options("selectedurl")= ind;
  }
  return urlsDefault[ind];
}

function getSavedUrls() {
  var urlsTmp = new Array();
  if(options.exists("length")) {
    var len = parseInt(options("length"));

    for(i=0;i<len;i++)
      urlsTmp[i] = options("url"+i);
  }
  urlsDefault = urlsTmp;
}

function saveUrls() {
  var urlsTmp = urlsDefault;
  var len = urlsTmp.length;
  options("length") = len;
  for(i=0;i<len;i++) {
    options("url"+i) = urlsTmp[i];
  }
}
function addUrl(url) {
  urlsDefault[urlsDefault.length] = url;
  saveUrls();
}

function removeUrl(url) {
  if(urlsDefault.length==1)
   return;
  var i=0;
  for(;i<urlsDefault.length;i++)
    if(urlsDefault[i] == url)
      break;
  for(;i<urlsDefault.length-1;i++)
    urlsDefault[i] = urlsDefault[i+1];
 
  urlsDefault.length = urlsDefault.length -1;
  
  saveUrls();
}



var item_indx= 0;


function ShowOptionsDlg(wnd) {
  //wnd.AddControl(gddWndCtrlClassLabel, 0, "", "Title", 10, 5, 50, 20);
  // var ctrl_title = wnd.AddControl(gddWndCtrlClassEdit, 1, "title", "", 70, 5, 150, 20);

  wnd.AddControl(gddWndCtrlClassLabel, 0, "", "Feed Url", 10, 20, 50, 45);
  var ctrl_url = wnd.AddControl(gddWndCtrlClassEdit, 2, "url", "", 70, 20, 200, 20);

  var ctrl_add = wnd.AddControl(gddWndCtrlClassButton, gddWndCtrlTypeButtonPush,"btn_add", "&Add", 10, 50, 50, 20);
  ctrl_add.onClicked = OnClickOptionsAdd;
 
  var ctrl_remove = wnd.AddControl(gddWndCtrlClassButton, gddWndCtrlTypeButtonPush, "btn_remove", "&Remove Selected", 70, 50, 90, 20);
  ctrl_remove.onClicked = OnClickOptionsRemove;
  //wnd.GetControl("btn_remove").onClicked = OnClickOptionsRemove;

  var list = wnd.AddControl(gddWndCtrlClassList, gddWndCtrlTypeListOpen, "urls", urlsDefault, 10, 80, 280, 100);
  list.onChanged = setSelectedUrl;
  list.value = getSelectedUrl();
  //list.value = GetCountry();
  // handlers
  wnd.onClose = OptionsDlgClosed;  
}

function OnClickOptionsAdd(wnd, control){
  //var title = wnd.GetControl("title").value;
  var url = wnd.GetControl("url").value;
  addUrl(url);
  wnd.GetControl("urls").text = urlsDefault;
  
}

function OnClickOptionsRemove(wnd, control) {
  var url_toRemove = wnd.GetControl("urls").value;
  removeUrl(url_toRemove);
  wnd.GetControl("urls").text = urlsDefault;
}

function OptionsDlgClosed(wnd, code) {
  if (code == gddIdCancel)
    return;
  else{
    view_onOpen();
  }
}


function nextFeed() {
 
 var selectedurl = parseInt(options("selectedurl"));
 selectedurl ++;
 if(selectedurl >= urlsDefault.length)
   selectedurl = 0;
 options("selectedurl") = selectedurl;

view_onOpen();
}

function prevFeed(){

 var selectedurl = parseInt(options("selectedurl"));
 selectedurl --;
 if(selectedurl <= 0)
   selectedurl = urlsDefault.length-1;
 options("selectedurl") = selectedurl;
 

 view_onOpen();
}

utils.setInterval(view_onOpen, 1000 * interval);

function view_onOpen()
{
  if(!options.exists("length"))
    saveUrls();
  else{
    getSavedUrls(); 
  }
  if(framework.system.network.online || framework.system.network.wireless.connected){
		FetchAndParse(getSelectedUrl());
  }
}

function setSelectedUrl(wnd, control) { 
   var tmp = control.value;
   var i =0;
   for(;i<urlsDefault.length;i++)
       if(tmp==urlsDefault[i])
          break;
   options("selectedurl") = i;
}

//Fetches the Rss feed from the selected site.
function FetchAndParse(url) {
  div_loading.visible = true;
  httpReq = new XMLHttpRequest();
  httpReq.onreadystatechange = OnRssFeed;
  httpReq.open("GET", url, true);
  httpReq.send();  
}



function OnRssFeed() {
   if(framework.system.network.online || framework.system.network.wireless.connected){
   if(httpReq.readyState==4){

      if(httpReq.status==200){
         doc = new DOMDocument();
         doc.loadXML(httpReq.responseText);
//Image
         var expImg = doc.getElementsByTagName("image")[0];
         var imgUrl = "";
         if(expImg!=null){
           img_icon.visible = true;
           cnArea.y = 31;
           cnArea.height = 163;

 	   for(var node = expImg.firstChild; node!=null ; node = node.nextSibling){
             if(node.nodeName == "url")
                  imgUrl = node.firstChild.nodeValue;
	     else if(node.nodeName == "link")
                  imgLink = node.firstChild.nodeValue;
	    }
           //Load Image and set it to the img tag
           loadAndSetImage(imgUrl);
         }else {
           img_icon.visible = false;
           cnArea.y = 1;
           cnArea.height = 191;
         }
       //Title (channel->title)
 
         var channel = doc.getElementsByTagName("channel")[0];
         var feedTitle = "";
         if(channel!=null && channel!=undefined){
           var tit = channel.getElementsByTagName("title")[0];
           feedTitle = tit.firstChild.nodeValue!=null && tit.firstChild.nodeValue!=undefined ? tit.firstChild.nodeValue : "";
         }
           lbl_feedtitle.innerText = feedTitle;
           lbl_feedtitle.enabled = true;
           lbl_feedtitle.tooltip = feedTitle;


         var items = doc.getElementsByTagName("item");
         //debug.trace("Item Count"+items.length);
				 cnArea.removeAllContentItems();
         if(items.length<=0){
						alert("Feed is empty! or Invalid!");
            
         }else{
         if(items.length>0) {
            cnArea.contentFlags = gddContentFlagHaveDetails;
            try{
              for(var i=items.length-1;i>=0;i--){ 
               var title, link, description,pubDate,date,guid;
               for (var node = items[i].firstChild; node != null; node = node.nextSibling) {
                   if (node.nodeName == "title")
                      title = node.firstChild.nodeValue;
                   else 
                   if(node.nodeName== "link")
                      link = node.firstChild.nodeValue;
                   else
                   if(node.nodeName == "description")
                      description = node.firstChild.nodeValue;
                   else
                   if(node.nodeName == "pubDate")
                      pubDate = node.firstChild.nodeValue;
                   else
                   if(node.nodeName == "dc:date")
                      date = node.firstChild.nodeValue;
                   else
                   if(node.nodeName == "guid")
                      guid = node.firstChild.nodeValue;                 
                }

/////////////////
             var curItem = new ContentItem();
             //curItem.onDrawItem = AddBullet;
             curItem.layout = gddContentItemLayoutNews;
             curItem.flags = gddContentItemFlagNoRemove;
             curItem.onDetailsView = OnDetailsView;
             cnArea.AddContentItem(curItem, gddItemDisplayInSidebar);

             var titleStr = new String(title);
 
             curItem.heading = titleStr;
             curItem.snippet = description;

             //debug.trace("pubDate: " + pubDate);

             if(pubDate!=null && pubDate!=undefined){
               var tm = new Date(pubDate);
               tm.setMinutes(tm.getMinutes() + tm.getTimezoneOffset());
               curItem.time_created = tm.getVarDate();
             }
             curItem.open_command = link;

             cnArea.AddContentItem(curItem, gddItemDisplayInSidebar);
            }
           }catch(Exception){debug.trace(Exception.toString());}
          }
					div_loading.visible = false;
         }
      }//if status is 200
			else{
				var tmpUrl = getSelectedUrl();
				alert("Wrong feed!!\n"+tmpUrl+"\nDeleting from list");
				div_loading.visible = false;
				removeUrl(getSelectedUrl());  
      }//else
   }//if readyState == 4
   }//if network connected
}

function AddBullet(item, target, graphics, x, y, width, height) {
  var bgColor = "#000000";
  graphics.DrawRect(x+4, y+3, x+3, 3, bgColor, bgColor);
  graphics.DrawText(x+6, y, width, height, "  " + item.heading, gddColorNormalText, 
   gddTextFlagWordBreak, gddFontNormal);
}

function loadAndSetImage(imgUrl) {
    var httpReq2 = new XMLHttpRequest();
    httpReq2.onreadystatechange = function() {
        if(httpReq2.readyState==4 && httpReq2.status==200){
             img_icon.visible = true;
             img_icon.src = httpReq2.responseStream; 
	      //div_img.background = httpReq2.responseStream;
        }
    };
    httpReq2.open("GET", imgUrl, true);
    httpReq2.send();
}
//Details view handler. Formats the html code and displays
function OnDetailsView(item) {
  var htmlcontent = "<html><body>"  +item.snippet +"</body></html>";
  
  var control = new DetailsView();
 
  control.SetContent(item.source, item.time_created, htmlcontent, true, item.layout);
  control.html_content = true;

  var details = new Object();
  details.details_control = control;
  
  return details;
}
